<?php

namespace app\admin\controller;

use app\admin\model\BatOrderModel;
use app\admin\model\TeamModel;
use cmf\controller\AdminBaseController;
use think\Request;
use think\Db;
use app\admin\model\BatMatchModel;
use app\admin\model\VictoryModel;
use app\admin\model\GiveModel;
use app\admin\model\SizeModel;
use api\guess\Services\RefundService;


class BatMatchController extends AdminBaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request, BatMatchModel $model)
    {
        $param = $request->param();
        $list = $model
            ->with('teamMain,teamPass')

            ->where(function($query) use($param){
                if(isset($param['team_name']) && !empty($param['team_name'])){
                    $team =TeamModel::where('team_name','like','%' . $param['team_name'].'%')->column('id');
                    $query->whereIn('team_pass_id',$team);
                    $query->whereIn('team_pass_id',$team);
                }
                if(isset($param['match_time']) && !empty($param['match_time'])){
                    $query->whereBetweenTime('match_time' , $param['match_time'] );
                }
                if(isset($param['type']) && !empty($param['type'])){
                    $query->whereLike('type',$param['type']);
                }
            })
            ->field('*')
            ->order('create_time desc')
            ->paginate(null,false,['query'=>$param]);


        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);

        return $this->fetch();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function add()
    {
       // $this->assign('lea_match',LeaMatchModel::all());
        return $this->fetch();
    }



    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $this->save_and_update($request->param(),new BatMatchModel());

        $this->success('添加成功!', url('BatMatch/index'));
    }

    /**
     *
     * ajax获取烈性的球队
     * @param  int  $id
     * @return \think\Response
     */
    public function getTeam(Request $request)
    {
       //return LeaMatchModel::get($request->id)->teams;
        return TeamModel::where('type',$request->type)->select();
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
       if(!$data = BatMatchModel::get($id)){
           $this->error('数据不存在');
       }
        $this->assign('data',$data);
        //$this->assign('lea_match',LeaMatchModel::all());
        return $this->fetch();
    }


    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request,BatMatchModel $model )
    {

        if(! $bat = BatMatchModel::get($request->id)){
            $this->error('数据不存在');
        }
        $data = $request->param();
        if($data['main_score'] == '' && $data['pass_score'] ==''){
            //剔除主客场比分，不保存
            unset($data['main_score']);
            unset($data['pass_score']);
        }else{
            if ($bat->status !== BatMatchModel::EVEMT_STATUS_RESULTFUL){
                //修改状态成已经出结果
                $data['status'] = BatMatchModel::EVEMT_STATUS_RESULTFUL;
            }
        }
        $this->save_and_update($data,new BatMatchModel(),$request->id);
        //退款
        if (!empty($data['main_score']) && !empty($data['pass_score']) && $bat->status !== $model::EVEMT_STATUS_RESULTFUL){
            $refundService = new RefundService();
            $refundService->match_result($bat->id);
        }
        $this->success('添加成功!', url('BatMatch/index'));

    }
    /**
     * @param $data
     * @param $model
     * @param int $id
     * 保存和更新的方法
     */
    public function save_and_update($data, $model,$id=0){
        if($data['team_main_id'] == $data['team_pass_id']){
            $this->error('主客场球队不能相同');
        }
        if (!empty($data['bet_end_time']) && $data['bet_end_time'] <= $data['match_time']){
            $this->error('投注结束时间必须大于比赛开始时间');
        }
        $data['match_time'] = strtotime($data['match_time']);

        $data['bet_end_time'] = strtotime($data['bet_end_time']);

        Db::transaction(function () use($data,$model,$id){
            if($id){
                //对战表更新数据
                $bat = $model->allowField(true)->update($data,['id'=>$data['id']]);

            }else{
                //对战表插入数据
                $bat = $model->allowField(true)->create($data);
            }
            //猜胜负插入数据
            $this->guessing(['v_main_odd','v_middle_odd','v_pass_odd'],new VictoryModel(),$data,$bat->id);
            //猜让球插入数据
            $this->guessing(['g_main_odd','g_give_name','g_give_num','g_pass_odd'],new GiveModel(),$data,$bat->id);
            //猜大小插入数据
            $this->guessing(['s_main_odd','s_size_num','s_pass_odd'],new SizeModel(),$data,$bat->id);
        });

    }


    /**
     * @param $param
     * @param $model
     * @param $data
     * @return bool
     * 竞猜游戏插入数据
     */
    public function guessing($param,$table,$data,$bid){

        foreach ($param as $key => $value){
            if ($data[$value]){
                $array[$value]  = $data[$value];
            }else{
                return false;
            }
        }
        $array['bat_id'] = $bid;
        if($result = $table::where('bat_id',$bid)->find()){
            $table->allowField(true)->update($array,['id'=>$result['id']]);
        }else{
            $table->allowField(true)->create($array);

        }
    }


    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (! $data = BatMatchModel::where('id',$id)->find()){
            $this->error('数据不存在');
        }

        $home = Db::table('cmf_home')->where('bat_id',$id)->find();
        $pre = Db::table('cmf_pre_result')->where('bat_id',$id)->find();

        if ($home || $pre){
            $this->error('数据已绑定聊吧，不能删除');
        }

        BatMatchModel::destroy($id);

        $this->success('删除成功!');


    }
}
